package l1j.opqlo.NewSystem.Extension;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import l1j.opqlo.NewSystem.A_ColorMessage;
import l1j.opqlo.Server.L1World.L1World;
import l1j.server.server.model.Getback;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.L1Teleport;
import l1j.server.server.model.Instance.L1DoorInstance;
import l1j.server.server.model.Instance.L1EffectInstance;
import l1j.server.server.model.Instance.L1FieldObjectInstance;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.Instance.L1PetInstance;
import l1j.server.server.model.Instance.L1SummonInstance;
import l1j.server.server.serverpackets.S_CharVisualUpdate;
import l1j.server.server.serverpackets.S_EffectLocation;
import l1j.server.server.serverpackets.S_GreenMessage;
import l1j.server.server.serverpackets.S_MapID;
import l1j.server.server.serverpackets.S_OtherCharPacks;
import l1j.server.server.serverpackets.S_OwnCharPack;
import l1j.server.server.serverpackets.S_PacketBoxGame;
import l1j.server.server.serverpackets.S_RedMessage;
import l1j.server.server.serverpackets.S_RemoveObject;
import l1j.server.server.serverpackets.S_SkillIconGFX;
import l1j.server.server.serverpackets.S_Weather;
import l1j.server.server.utils.Random;

public class FireTest {

	private int _status;
	private int _boss1Type;
	private static int[]_boss1Id ={710069 , 710070};
	private int[]_boss1Loc={
			32741, 32883, 
			32741, 32906
	};
	private int[]_boss2Id ={};
	private int[]_boss2Loc={};

	private static int _trapId =710068;//	結界踏板
	private static int[]_trapX = {32713,32695,32695,32682,32688,32713,32682,32688,32713 };
	private static int[]_trapY = {32865,32867,32870,32876,32884,32915,32914,32906,32875 };
	private int _delayTime;
	private int _mapId;

	private boolean _gameover;

	private L1PcInstance[] _pcParty;

	public List<String> _pcNameList = new ArrayList<String>();
	private List<L1PcInstance> _pcList = new ArrayList<L1PcInstance>();

	private TimerThread thread ;
	private boolean _isBegin;


	public FireTest(final L1PcInstance pc , final int mapid){
		this._pcParty = pc.getParty().getMembers();
		for (final L1PcInstance element : this._pcParty) {
			this.addPcList(element);
			this._pcNameList.add(element.getName());// 紀錄參加玩家的名稱
			//			TreasureMaster.Game1_pcList.put(element.getName(), this);
			_mapId = mapid;
		}
		this.GreenMessage("準備進入副本，10秒後將自動傳送。", true, 10);
		_delayTime =10;
		_status =1;
		thread = new TimerThread(1800);
		thread.begin();
		_isBegin = true;
	}
	/** 列表加入正在副本的玩家 */
	public boolean addPcList(final L1PcInstance pc) {
		if (this._gameover) {
			return false;
		}
		if (this._pcList.contains(pc)) {
			this._pcList.remove(pc);
		}
		this._pcList.add(pc);
		pc.inQuestGame = true;
		return true;
	}

	public void ItemAction(){
		_status = 3;
	}


	public class TimerThread  extends TimerTask {

		private int _time;

		public TimerThread(final int time){
			this._time = time;
		}
		private void begin(){
			final Timer timer = new Timer();
			timer.scheduleAtFixedRate(this, 1000, 1000);//每秒一次
		}

		@Override
		public void run() {
			switch(_status){
			case 1://玩家開始入場 等候10秒
				if(_delayTime==0){
					GreenMessage("副本將於10秒後開始，請在時間內擊殺怪物獲取【魔族密令】來召喚出副本BOSS。", true, 10);
					Teleport(32728, 32894 , 32895 , 0);
					_status = 2;
					_delayTime = 10;
					_isBegin = false;
				}
				break;

			case 2://第一波小怪開始 創怪
				if(_delayTime==0){
					GreenMessage("副本開始!!請擊殺怪物獲取【魔族密令】來召喚出副本BOSS。", true,_time);
					TreasureMaster.getInstance().spawn(
							77072026,//_ItemId,
							710066	,//_npcId[i],火焰強弩手
							300,
							0,
							0,
							(short) _mapId, 0, 0, false);
					_status =0;
				}
				break;
			case 3://第一波BOSS
				resetTreasure();
				final int chance = Random.nextInt(100)+1;
				final S_EffectLocation packet;
				if(chance>50){	
					RedMessage("死亡的氣息瞬間侵入你的腦中...");
					Teleport(32736 , 32880 , 32888 , 2);
					packet =new S_EffectLocation(32741, 32883, 1837);
					_boss1Type = 1;
				}else{
					RedMessage("!!!!!!!.....");
					Teleport(32736 , 32903 , 32911 , 2);
					packet =new S_EffectLocation(32741, 32906, 1837);
					_boss1Type =2;
				}
				_status =4;
				_delayTime =3;
				for (final L1PcInstance ppc : _pcList) {
					if (ppc != null) {
						ppc.sendPackets(packet);
					}
				}
				break;
			case 4:
				if(_delayTime==0){
					if(_boss1Type == 1){
						TreasureMaster.getInstance().spawn(
								0,//_ItemId,
								710069	,//_npcId[i],死亡
								1,
								_boss1Loc[0],
								_boss1Loc[1],
								(short) _mapId, 0, 0, true);
					}else{
						TreasureMaster.getInstance().spawn(
								0,//_ItemId,
								710070	,//_npcId[i],混沌
								1,
								_boss1Loc[2],
								_boss1Loc[3],
								(short) _mapId, 0, 0, true);	
					}
					_status =0;
				}
				break;

			case 5:
				RedMessage("[溫柔的聲音]:勇士們請尋找可以打開結界的機關，我已經幫你們點亮它們了。");
				final int setNumber =Random.nextInt(_trapX.length);
				L1EffectInstance eff = null;
				for(int i=0; i <_trapX.length; i++){
					eff =(L1EffectInstance) TreasureMaster.getInstance().spawn(
							0,//_ItemId,
							_trapId	,//_npcId
							1,
							_trapX[i],
							_trapY[i],
							(short) _mapId, 0, 0, false)[0];
//					eff._firetest = FireTest.this;
//					if(i == setNumber){
//						eff._isMobSpawn = false;
//					}else{
//						eff._isMobSpawn = true;
//					}
				}
				_status =0;
				break;
			case 6:
				GreenMessage("測試結束。", false, 0);
				_status = 99;
				break;
			case 99: //結束副本60秒倒數
				_gameover = true;
				resetTreasure();
				GreenMessage("副本結束，60秒後所有玩家將自動傳送離場。", true, 60);
				_status =0;
				_time = 60;
				break;
			}


			if(_delayTime >0){
				_delayTime--;
				updateTime(_delayTime);
			}else{
				if(_time <=0){
					PcGoHome();// 傳送玩家離場
					_pcNameList.clear();
					_pcList.clear();
					clearPet();
					this.cancel();
				}else{				
					_time--;
					updateTime(_time);
				}
			}
			if(_pcList.isEmpty()){
				_gameover = true;
				_pcNameList.clear();
				_pcList.clear();
				this.cancel();
				resetTreasure();
				clearPet();
			}
		}
	}

	/** 特定NPC死亡後觸發任務 */
	public void npdDead(final int npcid) {
		if(npcid == _boss1Id[0] || npcid == _boss1Id[1]){
			_status = 5;
		}
	}


	public void TrapAcvion(final int x , final int y ,final boolean spawn){
		if(spawn){
			TreasureMaster.getInstance().spawn(0,710067, 6, x, y,(short) this._mapId, 5, 0, false);
		}else{
			if(_status ==0){
				_status =6;
			}
		}
	}
	private void updateTime(final int time){
		Iterator<L1PcInstance> ite = this._pcList.iterator();
		while(ite.hasNext()){
			final L1PcInstance msgPc = ite.next();
			if(	!_isBegin && ( msgPc.getNetConnection() ==null || msgPc.getMapId() != this._mapId ) ){
				ite.remove();
			}else{
				msgPc.sendPackets(new S_SkillIconGFX(71, time));// opqlo 特殊地圖計時顯示
			}
		}
	}


	/** 傳送玩家 */
	private void Teleport(int x, int y, final int yy, final int head) {
		final int srcy = y;
		L1PcInstance pc;
		for (int i = 0; i < this._pcList.size(); i++) {
			pc = this._pcList.get(i);
			if (!pc.isDead()) {
				L1Teleport.teleport(pc, x, y, (short) this._mapId, head, true);
				if (y <= yy) {
					x--;
					y = srcy;
				}
				y--;
			}
		}
		// L1Teleport.teleport(pc, loc, head, effectable)
	}
	/** 發送綠色訊息(是否含時間) **/
	private void GreenMessage(final String msg, final boolean haveTime,
			final int Time) {
		for (final L1PcInstance MsgPc : this._pcList) {
			if (MsgPc != null) {
				MsgPc.sendPackets(new S_GreenMessage(msg));
				MsgPc.sendPackets(new A_ColorMessage(15, msg));
				if (haveTime && Time > 0) {
					MsgPc.sendPackets(new S_SkillIconGFX(71, Time));// opqlo
					// 特殊地圖計時顯示
				}
			}
		}
	}
	private void PcGoHome() {
		// 將玩家傳出副本地圖
		for (final Object obj : L1World.getInstance().getVisibleObjects((short) _mapId).values()) {
			if (obj instanceof L1PcInstance) {
				final L1PcInstance pc = (L1PcInstance) obj;
				if (pc != null) {
					/** 刪除副本通關道具(禁止帶出) */
					//					final L1PcInventory inv = pc.getInventory();
					//					final L1ItemInstance item = inv.findItemId(this._ItemId);
					//					if (item != null) {
					//						pc.getInventory().removeItem(item);
					//					}

					if (pc.isDead()) {
						this.reStartPlayer(pc);
					} else {
						// 傳送至威頓村
						L1Teleport.teleport(pc, 33710, 32521, (short) 4,pc.getHeading(), true);
						// pc.sendPackets(new S_SkillIconGFX(71, 0));//opqlo
						// 特殊地圖計時顯示

						pc.sendPackets(new S_PacketBoxGame(
								S_PacketBoxGame.STARTTIMECLEAR));
					}
				}
			}// 刪除副本內的物品
			else if (obj instanceof L1Inventory) {
				final L1Inventory inventory = (L1Inventory) obj;
				inventory.clearItems();
			}
		}
	}

	/** 發送紅色訊息 **/
	private void RedMessage(final String msg) {
		for (final L1PcInstance MsgPc : this._pcParty) {
			if (MsgPc != null) {
				MsgPc.sendPackets(new S_RedMessage(msg));
			}
		}
	}

	// 重置副本
	private void resetTreasure() {

		for (final Object obj : L1World.getInstance()
				.getVisibleObjects((short) _mapId).values()) {

			// 門關閉
			if (obj instanceof L1DoorInstance) {
				final L1DoorInstance door = (L1DoorInstance) obj;
				door.close();
			}
			// 刪除副本內的怪物
			else if (obj instanceof L1NpcInstance) {
				final L1NpcInstance npc = (L1NpcInstance) obj;
				if (npc.getMaster() == null) {
					npc.deleteMe();
				}
			} else if (obj instanceof L1FieldObjectInstance) {
				final L1FieldObjectInstance field = (L1FieldObjectInstance) obj;
				field.deleteMe();
			}

		}

	}

	// 副本內死亡的玩家重新開始
	private void reStartPlayer(final L1PcInstance pc) {
		pc.stopPcDeleteTimer();

		final int[] loc = Getback.GetBack_Location(pc, true);

		pc.removeAllKnownObjects();
		pc.broadcastPacketAll(new S_RemoveObject(pc));

		pc.setCurrentHp(pc.getLevel());
		pc.set_food(40);
		pc.setDead(false);
		pc.setStatus(0);
		L1World.getInstance().moveVisibleObject(pc, loc[2]);
		pc.setX(loc[0]);
		pc.setY(loc[1]);
		pc.setMap((short) loc[2]);
		pc.sendPackets(new S_MapID(pc.getMapId(), pc.getMap().isUnderwater()));
		pc.broadcastPacketAll(new S_OtherCharPacks(pc));
		pc.sendPackets(new S_OwnCharPack(pc));
		pc.sendPackets(new S_CharVisualUpdate(pc));
		pc.startHpRegeneration();
		pc.startMpRegeneration();
		pc.sendPackets(new S_Weather(L1World.getInstance().getWeather()));
		if (pc.getHellTime() > 0) {
			pc.beginHell();
		}
	}
	/** 清除副本殘留的寵物、召喚獸 **/
	private void clearPet() {
		for (final Object obj : L1World.getInstance().getVisibleObjects((short) this._mapId).values()) {
			if (obj instanceof L1SummonInstance) {
				final L1SummonInstance summon = (L1SummonInstance) obj;
				final L1PcInstance pc = (L1PcInstance) summon.getMaster();
				if (pc != null) {
					pc.getPetList().remove(summon.getId());
				}
				summon.deleteMe();
			} else if (obj instanceof L1PetInstance) {
				final L1PetInstance pet = (L1PetInstance) obj;
				final L1PcInstance pc = (L1PcInstance) pet.getMaster();
				if (pc != null) {
					pc.getPetList().remove(pet.getId());
				}
				pet.stopFoodTimer(pet); // 停止飽食度計時
				pet.setDead(true);// 寵物認知
				pet.dropItem();
				pet.deleteMe();
			}
		}
	}
}
